﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PanasonicWarranty.Business;

namespace PanasonicWarranty.UI
{
    public partial class GroupManagement : BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!IsPostBack)
            {
                if (!AllowCreateGroup() && !AllowEditGroup() && !AllowDeleteGroup())
                {
                    RedirectToPage(AccessDeniedURL);
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDataGroup();
            }
        }

        private void BindDataGroup()
        {
            rptGroup.DataSource = DB.pepsi_Groups;
            rptGroup.DataBind();
        }

        private void BindDataRole(int? groupId)
        {
            rptRole.DataSource =
                DB.pepsi_Roles.Select(p => new
                {
                    p.RoleId,
                    p.RoleName,
                    p.Description,
                    Checked = DB.pepsi_Role_Groups.Any(q => q.RoleID == p.RoleId && q.GroupID == groupId)
                });
            rptRole.DataBind();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                int groupId = 0;
                int.TryParse(hdfGroupId.Value, out groupId);
                string groupName = txtGroupName.Text.Trim();
                string description = txtDescription.Text;
                if (CheckExistGroup(groupId, groupName))
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "message", "alert('The group already exist!');", true);
                    return;
                }
                pepsi_Group objGroup = null;
                switch (Action.Value)
                {
                    case "Edit":
                        if (!AllowEditGroup())
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('You dont't have permission!');", true);
                            return;
                        }
                        objGroup = DB.pepsi_Groups.FirstOrDefault(p => p.GroupID == groupId);
                        if (objGroup != null)
                        {
                            objGroup.GroupName = groupName;
                            objGroup.Description = description;
                        }
                        break;
                    case "Add":
                        if (!AllowCreateGroup())
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('You dont't have permission!');", true);
                            return;
                        }
                        objGroup = new pepsi_Group()
                        {
                            GroupName = groupName,
                            Description = description
                        };
                        DB.pepsi_Groups.InsertOnSubmit(objGroup);
                        break;
                    default: return;
                }
                //Delete old Role
                if (Action.Value == "Edit")
                    DB.pepsi_Role_Groups.DeleteAllOnSubmit(DB.pepsi_Role_Groups.Where(p => p.GroupID == groupId));
                //Re add roles
                foreach (RepeaterItem item in rptRole.Items)
                {
                    CheckBox chk = (CheckBox)item.FindControl("chkCheck");
                    if (chk.Checked)
                    {
                        HiddenField hdf = (HiddenField)item.FindControl("hdfRole");
                        pepsi_Role_Group newObj = new pepsi_Role_Group()
                        {
                            pepsi_Group = objGroup,
                            RoleID = int.Parse(hdf.Value)
                        };
                        DB.pepsi_Role_Groups.InsertOnSubmit(newObj);
                    }
                }
                DB.SubmitChanges();
                BindDataGroup();
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"" + ex.Message + "\");", true);
            }
        }

        protected void rptGroup_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                int groupId = Convert.ToInt32(e.CommandArgument);
                var objGroup = DB.pepsi_Groups.FirstOrDefault(p => p.GroupID == groupId);
                switch (e.CommandName)
                {
                    case "Edit":
                        if (!AllowEditGroup())
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('You dont't have permission!');", true);
                            return;
                        }
                        Action.Value = "Edit";
                        if (objGroup != null)
                        {
                            hdfGroupId.Value = groupId.ToString();
                            txtGroupName.Text = objGroup.GroupName;
                            txtDescription.Text = objGroup.Description;
                            BindDataRole(groupId);
                        }
                        ClientScript.RegisterStartupScript(this.GetType(), "", "dialog();", true);
                        break;
                    case "Delete":
                        if (!AllowDeleteGroup())
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('You dont't have permission!');", true);
                            return;
                        }
                        if (groupId == 1)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Cannot delete administrators group!');", true);
                            return;
                        }
                        //Check User group
                        if (DB.pepsi_User_Groups.Any(p => p.GroupID == groupId))
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Already user in this group, cannot delete!');", true);
                            return;
                        }
                        //Delete Role group
                        DB.pepsi_Role_Groups.DeleteAllOnSubmit(DB.pepsi_Role_Groups.Where(p => p.GroupID == groupId));
                        //Delete group
                        DB.pepsi_Groups.DeleteOnSubmit(DB.pepsi_Groups.FirstOrDefault(p => p.GroupID == groupId));
                        DB.SubmitChanges();
                        break;
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"" + ex.Message + "\");", true);
            }
        }

        protected void lbtnAddNew_Click(object sender, EventArgs e)
        {
            if (!AllowCreateGroup())
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('You dont't have permission!');", true);
                return;
            }
            Action.Value = "Add";
            txtGroupName.Text = string.Empty;
            txtDescription.Text = string.Empty;
            BindDataRole(null);
            ClientScript.RegisterStartupScript(this.GetType(), "", "dialog();", true);
        }

        private bool CheckExistGroup(int groupId, string groupName)
        {
            if (DB.pepsi_Groups.Any(p => p.GroupID != groupId && p.GroupName == groupName))
                return true;
            return false;
        }
    }
}